/**
 * Author: Lee Gauthier
 * 
 * 
 * 
 */


import javax.sound.midi.*;

public class GuitarMidi{
	
	private int prevNote;

	private MidiDevice mapleOut;
	private MidiDevice.Info[] info;
	private Receiver rec;
	
	private ShortMessage noteOff;
	private ShortMessage noteOn;
	private ShortMessage pitchBend;
	private ShortMessage modWheel;
	
	public GuitarMidi() throws MidiUnavailableException, InvalidMidiDataException
	{	
		this.prevNote = 60;
		
		this.info = MidiSystem.getMidiDeviceInfo();
		this.mapleOut = findMaple();
		this.mapleOut.open();
		this.rec = mapleOut.getReceiver();
		
		this.noteOn = new ShortMessage();
		this.noteOff = new ShortMessage();
		this.pitchBend = new ShortMessage();
		this.modWheel = new ShortMessage();
		
	}
	
	private MidiDevice findMaple() throws MidiUnavailableException
	{
		MidiDevice temp = null;
		for(int i = 0; i < info.length; i++){
			if(info[i].toString().equals("Maple Midi Out: Port 1")){
				temp = MidiSystem.getMidiDevice(info[i]);
			}
		}
		if(temp == null){
			System.exit(1);
		}
		return temp;
	}

	public void sendNote(int note, int velocity) throws InvalidMidiDataException, InterruptedException
	{
		this.noteOff.setMessage(128 , prevNote , 0 );
		this.noteOn.setMessage(ShortMessage.NOTE_ON, note , velocity );
		
		Thread.sleep(5);
		this.noteOff.setMessage(128 , this.prevNote , 0 );
		this.rec.send(this.noteOff, -1);
		Thread.sleep(5);
		this.rec.send(this.noteOn,-1);
		this.prevNote = this.noteOn.getData1();
	}
	
	public void noteOff() throws InvalidMidiDataException, InterruptedException
	{
		this.noteOff.setMessage(ShortMessage.NOTE_OFF , prevNote , 0 );
		
		Thread.sleep(5);
		this.noteOff.setMessage(ShortMessage.NOTE_OFF , prevNote , 0 );
		this.rec.send(noteOff, -1);
		
		this.prevNote = this.noteOff.getData1();
	}

	public void sendPitchBend(int bend) throws InterruptedException, InvalidMidiDataException 
	{
		Thread.sleep(5);
		this.pitchBend.setMessage(ShortMessage.PITCH_BEND, 0 , 64-bend);
		if(bend != 0)
			this.rec.send(pitchBend, -1);
	}

	public void mod(int value) throws InvalidMidiDataException, InterruptedException {
		Thread.sleep(5);
		this.modWheel.setMessage(170, value , value);
		this.rec.send(modWheel, -1);
	}
}